package com.fesine.ssh.dao.impl;

import com.fesine.ssh.dao.SalesOrderDao;
import com.fesine.ssh.model.SaleItem;
import com.fesine.ssh.model.SalesOrder;
import com.fesine.ssh.util.ShopException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Set;

/**
 * Created by Fesine on 2016/2/22.
 */
@Repository("salesOrderDao")
public class SalesOrderDaoImpl implements SalesOrderDao {
    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }

    @Override
    public SalesOrder load(String id) {
        return (SalesOrder) this.getCurrentSession().load(SalesOrder.class,id);
    }

    @Override
    public SalesOrder get(String id) {
        return (SalesOrder) this.getCurrentSession().get(SalesOrder.class, id);
    }

    @Override
    public String save(SalesOrder entity) {
        Set<SaleItem> saleItemSet = entity.getSaleItems();
        double totalPrice = 0d;
        for (SaleItem saleItem : saleItemSet) {
            totalPrice += new BigDecimal(Double.valueOf(saleItem.getPrice()))
                    .multiply(new BigDecimal(Double.valueOf(saleItem.getNumber())))
                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
            this.getCurrentSession().save(saleItem);
        }
        entity.setTotalPrice(totalPrice);
        return (String) this.getCurrentSession().save(entity);
    }

    @Override
    public void update(SalesOrder entity) {
        this.getCurrentSession().update(entity);
    }

    @Override
    public void saveOrUpdate(SalesOrder entity) {
        this.getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(String id) {
        SalesOrder salesOrder = this.get(id);
        this.getCurrentSession().delete(salesOrder);
    }

    @Override
    public void flush() {
        this.getCurrentSession().flush();
    }

    @Override
    public void persist(SalesOrder entity) {
        this.getCurrentSession().persist(entity);
    }

    @Override
    public List<SalesOrder> findAll() {
        String hql = String.format("from SalesOrder order by orderId desc");
        List<SalesOrder> salesOrderList =
                this.getCurrentSession().createQuery(hql).list();
        return salesOrderList;
    }

    @Override
    public List<SalesOrder> findAll(int offset, int pageSize) {
        String hql = String.format("from SalesOrder order by orderId desc");
        Query query = this.getCurrentSession().createQuery(hql).setCacheable(true);
        query.setFirstResult(offset);
        query.setMaxResults(pageSize);
        List<SalesOrder> salesOrderList = query.list();
        return salesOrderList;
    }

    @Override
    public List<SalesOrder> findByEntity(SalesOrder entity) {
        String hql = toHql(entity);
        return this.getCurrentSession().createQuery(hql).setCacheable(true).list();
    }

    @Override
    public List<SalesOrder> findByEntity(SalesOrder entity, int offset, int pageSize) {
        String hql = toHql(entity);
        Query query = this.getCurrentSession().createQuery(hql).setCacheable(true);
        query.setFirstResult(offset);
        query.setMaxResults(pageSize);
        List<SalesOrder> salesOrderList = query.list();
        return salesOrderList;
    }

    /**
     * 将实体转换成hql查询语句
     *
     * @param salesOrder
     * @return
     */
    private String toHql(SalesOrder salesOrder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer hql = new StringBuffer("from salesOrder where 1=1 ");
        if (null != salesOrder.getOrderId()) {
            hql.append(" and orderId like '%" + salesOrder.getOrderId() + "%' ");
        }
        if (null != salesOrder.getUsername()) {
            hql.append(" and username like '%" + salesOrder.getUsername() + "%' ");
        }
        if (null != salesOrder.getQq()) {
            hql.append(" and qq like '%" + salesOrder.getQq() + "%' ");
        }
        if (null != salesOrder.getPhone()) {
            hql.append(" and phone like '%" + salesOrder.getPhone() + "%' ");
        }
        if (null != salesOrder.getAddress()) {
            hql.append(" and address like '%" + salesOrder.getAddress() + "%' ");
        }
        if (null != salesOrder.getRemark()) {
            hql.append(" and address like '%" + salesOrder.getRemark() + "%' ");
        }
        if (null != salesOrder.getStatus()) {
            hql.append(" and status = "+ salesOrder.getStatus());
        }
        if (null != salesOrder.getNullify()) {
            hql.append(" and nullify ="+ salesOrder.getNullify());
        }
        if (null != salesOrder.getOrdDate()) {
            hql.append(" and order >= '" + sdf.format(salesOrder.getOrdDate()) + "' ");
        }
        if (null != salesOrder.getUpdateDate()) {
            hql.append(" and order =< '" + sdf.format(salesOrder.getUpdateDate()) + "' ");
        }
        hql.append(" order by salesOrderId desc");
        return hql.toString();
    }

    @Override
    public SalesOrder findByOrderId(String orderId) {
        String hql = String.format("from SalesOrder where orderId='%s'",orderId);
        List<SalesOrder> list = this.getCurrentSession()
                .createQuery(hql).setCacheable(true).list();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }

    }

    /**
     * 修改订单状态值
     * @param orderId 订单号
     * @param status 订单审核状态
     * @param nullify 订单正常状态
     * @throws ShopException
     */
    @Override
    public void updateStatusByOrderId(String orderId, Integer status, Integer nullify) throws ShopException {
        if (null == status && null == nullify) {
            throw new ShopException("status和nullify值不能同时为空！");
        }
        StringBuffer hql = new StringBuffer(" update SalesOrder");
        if (null != status) {
            hql.append(" set status ="+status);
        }
        if (null != nullify) {
            hql.append(" set nullify ="+ nullify);
        }
        hql.append(" where orderId =" + orderId);
        this.getCurrentSession().createQuery(hql.toString()).executeUpdate();
    }

}
